class Solution
{
public:
    int firstCompleteIndex(vector<int> &arr, vector<vector<int>> &mat)
    {
        int m = mat.size();
        int n = mat[0].size();
        vector<int> numRow(m * n + 1);
        vector<int> numCol(m * n + 1);
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                numRow[mat[i][j]] = i;
                numCol[mat[i][j]] = j;
            }
        }

        vector<int> rowCount(n, 0);
        vector<int> colCount(m, 0);
        for (int i = 0; i < arr.size(); i++)
        {
            int row = numRow[arr[i]];
            int col = numCol[arr[i]];
            rowCount[col]++;
            colCount[row]++;
            if (rowCount[col] == m || colCount[row] == n)
            {
                return i;
            }
        }
        return -1;
    }
};